package so.shanku.essential.activity;

import android.app.AlertDialog.Builder;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;
import android.util.DisplayMetrics;
import android.util.Log;
import android.view.View;
import android.view.WindowManager;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.ImageView;
import aym.util.getservicesdata.GetServicesDataQueue;
import aym.util.getservicesdata.GetServicesDataUtil;
import aym.util.getservicesdata.GetServicesDataUtil.IGetServicesDataCallBack;
import aym.util.json.JsonMap;
import aym.util.json.JsonParseHelper;
import aym.util.sdcard.SdcardHelper;
import aym.util.versionup.IVersionSelectedCallBack;
import aym.util.versionup.VersionUpdateUtil;
import com.alipay.android.msp.demo.Keys;
import net.tsz.afinal.annotation.view.ViewInject;
import so.shanku.essential.R;
import so.shanku.essential.activity.base.BaseActivity;
import so.shanku.essential.app.MyApplication;
import so.shanku.essential.getdata.GetDataConfing;
import so.shanku.essential.getdata.GetDataQueue;
import so.shanku.essential.getdata.JsonKeys;
import so.shanku.essential.getdata.ShowGetDataError;
import so.shanku.essential.utils.Confing;
import so.shanku.essential.utils.ExtraKeys;
import so.shanku.essential.utils.Utils;

import java.io.File;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * Created by Administrator on 2015/8/17 0017.
 */
public class SplashActivity extends BaseActivity {

    @ViewInject(id = R.id.logo_msg_iv)
    private ImageView logo_msg_iv;
    @ViewInject(id = R.id.essential_logo_iv)
    private ImageView essential_logo_iv;
    @ViewInject(id = R.id.splash_line_iv)
    private ImageView splash_line_iv;
    // 版本升级的工具
    private VersionUpdateUtil util;
    // 内存卡管理的帮助类
    private SdcardHelper sdHelper;
    // 等待网络请求个数
    private int isCanNextActivity = 3;
    private boolean boolStartAnimation=true;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.splash_activity_layout);

        if (Utils.isHasLogin(mContext)) {
            isCanNextActivity = 3;
            getData_UserBrand(false);
        } else {
            isCanNextActivity = 2;
        }

        WindowManager wm = this.getWindowManager();
        int width = wm.getDefaultDisplay().getWidth();
        int height = wm.getDefaultDisplay().getHeight();
        DisplayMetrics metric = new DisplayMetrics();
        getWindowManager().getDefaultDisplay().getMetrics(metric);
        float density = metric.density;  // 屏幕密度（0.75 / 1.0 / 1.5）

        myApplication.setScreenWidth(width);
        myApplication.setScreenHeight(height);
        myApplication.setScreenDensity(density);
        util = VersionUpdateUtil.init(this);

        // 设置列表每页加载数量
        Confing.PageSize = 10;
        sdHelper = new SdcardHelper();

        next();
        //upversion();

        //upversion();

//		Confing.PayPartnerID = "2088911445763804";
//		Confing.PaySellerNo = "langyalife@meicheninfo.com";
//		Confing.PayPrivateKey = "MIICeAIBADANBgkqhkiG9w0BAQEFAASCAmIwggJeAgEAAoGBANcfCNPZO39kE4jOSLIc3skINZh+dSa+bKpWio1Oqhk3IE4r+j0bXH243bbJewJ3SkyWiT/WuxNKZdrCJ+Nhzg2+RJafNCKnPDh8IaMvK9zA0+ADfy1xZOAM6qif+32izkytZtcXi5ovjePMeJM4iwYk6tq+eyM2cnpA+h9QGp9BAgMBAAECgYBsaLxnHotoWIOrpuFluTzgrJ1t2xSo0MAsW255ZdI84NYL7wetsdM7nGVHT2QJSxqLXDWQkWM3hn+r7bpyUYCn6cfXYaSrb8KvQ7D7apTVz0ZgkAOszixJJ/0w2VePHEoWh2ZXV668JwOZfcY2v5pnEbpFJwK4byRGnXCTWtUFkQJBAPCkoh0QeG4zLXVS/1/pCN16cB404hkPZ/5sP4CbCpW82g+ePXuKgQwiaFfZOEknzCO5OMv+dhgQJ641EKfJ3q0CQQDk2XPXhM2CxZlx4X1zv37ZM5jJw4RrJzUBncX8aGQTq7Dg0zSqNjIHjlvfxx9sLG2KptESkgMOxIBmnAgUznllAkEAtUqCaz0GTZc2rwXZKItqR1i/cLJMh66onO82JBApuEcvTMbc8N6We+rMCyq1kb9utpcK5/wLQfOhwUdvBck6fQJBAMhFiLweC1+bH5rqs8f82LyqC9beVN8VM60TbrVigdo5EZTfIKKoxQWZzss6TkRzaPXC4Qq4XxaoXpntiKD0xIUCQQDwjuXWd792KHXPJxcSDFRZTszdYkzVOPzHisvzxh3oBPf2awnMNHpfl+CCEsUL0Q9D/t9rneOfp6RAoi/6sCvc";
//		Confing.RSA_ALIPAY_PUBLIC = "MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB";
//		Confing.PayNotifyUrl = "http://appservice.langyalife.com/AlipayNotify.aspx";
//		Keys.PRIVATE = Confing.PayPrivateKey;
//		Keys.DEFAULT_PARTNER = Confing.PayPartnerID;
//		Keys.DEFAULT_SELLER = Confing.PaySellerNo;
//		Keys.URL = Confing.PayNotifyUrl;
//		Keys.PUBLIC = Confing.RSA_ALIPAY_PUBLIC;
        // {"PartnerId":"2088301449344404","SellerNo":"naruko@jollywiz.com","Key":"121n7r4nziwhbh53zk04fgm1logay9po","PrivateKey":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDNKNUd/HK4h6eQVloWbLas+UfNyInZm9tKF9kXWMG50mzagXf/XwTqAmCoCubRaPVv6NTvVBdNs+54CwBiJbnBAju4Fj1c4YEt462bnoR9KQaYCBMj2H9YNBqlGrIAUiBSHPJVFmFlOWWokZ1ZjcdGMdIvlxQDIa6Wo0wZHuA4AQIDAQAB","PublicKey":"MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQCnxj/9qwVfgoUh/y2W89L6BkRAFljhNhgPdyPuBV64bfQNN1PjbCzkIM6qRdKBoLPXmKKMiFYnkd6rAoprih3/PrQEB/VsW8OoM8fxn67UDYuyBTqA23MML9q1+ilIZwBC2AQ2UBVOrFXfFl75p6/B5KsiNG9zpgmLCUYuLkxpLQIDAQAB","NotifyUrl":"/Alipay/Notify"}

        // CheckVersion(isintent, TAG);
    }


    @Override
    protected void onResume() {
        super.onResume();
        if(boolStartAnimation) {
            boolStartAnimation=false;
            startAnimation();
        }
    }

    Animation animin;
    Animation animAlphaIn;

    private void startAnimation() {
        Animation animout = AnimationUtils.loadAnimation(this, R.anim.zoom_exit);
        animAlphaIn = AnimationUtils.loadAnimation(this, R.anim.alpha_in);
        animin = AnimationUtils.loadAnimation(this, R.anim.zoom_enter);
        essential_logo_iv.startAnimation(animout);
        animout.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {
                animAlphaIn.cancel();
                animin.cancel();
                splash_line_iv.setVisibility(View.GONE);
                logo_msg_iv.setVisibility(View.GONE);
            }

            @Override
            public void onAnimationEnd(Animation animation) {
                startNextAnimation();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
        // startNextAnimation();
        animin.setAnimationListener(new Animation.AnimationListener() {
            @Override
            public void onAnimationStart(Animation animation) {

            }

            @Override
            public void onAnimationEnd(Animation animation) {
                jumpToNextOrSetCanJump();
            }

            @Override
            public void onAnimationRepeat(Animation animation) {

            }
        });
    }

    private void startNextAnimation() {
        essential_logo_iv.setVisibility(View.GONE);
        logo_msg_iv.setVisibility(View.VISIBLE);
        splash_line_iv.startAnimation(animin);
        logo_msg_iv.startAnimation(animAlphaIn);
        splash_line_iv.setVisibility(View.VISIBLE);

    }

    /**
     * 关注品牌接口
     */
    private void getData_UserBrand(boolean chearAllData) {

        Map<String, Object> params = new HashMap<String, Object>();
        params.put(GetDataQueue.Params_key, GetDataConfing.Key_Str);
        params.put("currentPage", 1);
        params.put("pageSize", 10000); //不分页请求
        params.put("UserInfoId", Utils.getUserId(this));
        GetDataQueue queue = new GetDataQueue();
        queue.setCallBack(callBackAttentionBrandCallback);
        queue.setActionName(GetDataConfing.GetAction_GetFocusVendorVO);
        queue.setWhat(GetDataConfing.what_GetFocusVendorVO);
        queue.setParamsNoJson(params);
        getDataUtil.getData(queue);
    }

    /**
     * 获取用户关注的品牌数据的返回信息
     */
    private GetServicesDataUtil.IGetServicesDataCallBack callBackAttentionBrandCallback = new GetServicesDataUtil.IGetServicesDataCallBack() {
        @Override
        public void onLoaded(GetServicesDataQueue entity) {
            if (entity.isOk()) {
                if (ShowGetDataError.isOkAndCodeIsNot1(mContext,
                        entity.getInfo())) {
                    if (entity.what == GetDataConfing.what_GetFocusVendorVO) {
                        ArrayList<JsonMap<String, Object>> data = (ArrayList<JsonMap<String, Object>>) JsonParseHelper.getJsonMap_List_JsonMap(
                                entity.getInfo(), JsonKeys.Key_Info);
                        MyApplication.getInstance().setAttentionBrands(data);
                    }
                }
            } else {
                //toast.showToast(R.string.async_datas_error);
                //ShowGetDataError.showNetError(mContext.this);
            }
            loadingToast.dismiss();
            jumpToNextOrSetCanJump();
        }
    };

    /**
     * 进入本界面停留2秒后做的事情
     */
    private void next() {

        if (sdHelper.ExistSDCard()) {
            File downLoadDir = new File(Confing.productPath);
            if (!downLoadDir.exists()) {// 判断文件是否存在，不存在就创建
                downLoadDir.mkdir();
            }
        }
        // String ip = "http://appservice.budayang.com";
        GetDataQueue queue = new GetDataQueue();
        // queue.setIp(ip);
        // String url = "http://budayangapp.hello36.com/"
        // + "ShoppingCartWebService.asmx/GetWebAlipayConfig";
        // queue.setActionName("/ShoppingCartWebService.asmx/GetWebAlipayConfig");
        // queue.setIp(ip);
        queue.setActionName(GetDataConfing.Action_GetConfigInfo);
        queue.setParams(new HashMap<String, String>());
        queue.setCallBack(new IGetServicesDataCallBack() {

            @Override
            public void onLoaded(GetServicesDataQueue entity) {
                if (entity.isOk()) {
                    Log.d(TAG, entity.getInfo());
                    List<JsonMap<String, Object>> info = JsonParseHelper
                            .getJsonMap_List_JsonMap(entity.getInfo(),
                                    JsonKeys.Key_Info);
                    if (info.size() == 0) {
                        toast.showToast(R.string.payinfo_invalid);
                        jumpToNextOrSetCanJump();
                    } else {
                        JsonMap<String, Object> config = info.get(0);
                        Confing.PayPartnerID = config
                                .getStringNoNull("PartnerID");
                        Confing.PaySellerNo = config
                                .getStringNoNull("SellerNo");
                        // Confing.PayNotifyUrl =
                        // "http://lxsservice.hello36.com/AlipayNotify.aspx";
                        // Confing.PayPartnerID = "2088611115979581";
                        // Confing.PaySellerNo = "jiebaohuitech@163.com";
                        Confing.PayPrivateKey = config
                                .getStringNoNull("PrivateKey");
                        Confing.RSA_ALIPAY_PUBLIC = config
                                .getStringNoNull("AlipayPublicKey");
                        Confing.PayNotifyUrl = config
                                .getStringNoNull("NotifyUrl");
                        Confing.ValidationCodeEffectionTime = config.getInt(
                                "ValidationCodeEffectionTime", 30);
                        Confing.PageSize = config.getInt("PageSize", 10);
                        /**
                         * 微信支付
                         */
                        Confing.WeiXinPaySignKey = config
                                .getStringNoNull("WeiXinPaySignKey");
                        Confing.WeiXinPartnerId = config
                                .getStringNoNull("WeiXinPartnerId");

                        Confing.WeiXinPartnerKey = config
                                .getStringNoNull("WeiXinPartnerKey");
                        Confing.WeiXinNotifyUrl = config
                                .getStringNoNull("WeiXinNotifyUrl");


                        // new UsedMobileSecurePayHelper(SplashActivity.this)
                        // .setPayInfo(Confing.PayPartnerID,
                        // Confing.PaySellerNo,
                        // Confing.PayPrivateKey,
                        // Confing.RSA_ALIPAY_PUBLIC,
                        // Confing.PayNotifyUrl);
                        if ("".equals(Confing.PayPartnerID)
                                || "".equals(Confing.PaySellerNo)
                                || "".equals(Confing.PayPrivateKey)
                                || "".equals(Confing.PayNotifyUrl)
                                || "".equals(Confing.RSA_ALIPAY_PUBLIC)) {
                            toast.showToast(R.string.payinfo_invalid);
                            jumpToNextOrSetCanJump();
                        }
                        Keys.PRIVATE = Confing.PayPrivateKey;
                        Keys.DEFAULT_PARTNER = Confing.PayPartnerID;
                        Keys.DEFAULT_SELLER = Confing.PaySellerNo;
                        Keys.URL = Confing.PayNotifyUrl;
                        Keys.PUBLIC = Confing.RSA_ALIPAY_PUBLIC;

                        Keys.WeiXinPaySignKey = Confing.WeiXinPaySignKey;
                        Keys.WeiXinPartnerId = Confing.WeiXinPartnerId;
                        Keys.WeiXinPartnerKey = Confing.WeiXinPartnerKey;
                        Keys.WeiXinNotifyUrl = Confing.WeiXinNotifyUrl;
                        jumpToNextOrSetCanJump();
                    }
                } else {
                    toast.showToast(R.string.neterror);
                    finish();

                }
            }
        });
        getDataUtil.getData(queue);
        // goMainActivity();
    }

    /**
     * 检测版本
     */
    private void upversion() {
        util = VersionUpdateUtil.init(this);
        if (!sdHelper.ExistSDCard()) {
            toast.showToast(R.string.nosdcard);
            jumpToNextOrSetCanJump();
        } else {
            util.doSelectVersion(GetDataConfing.ip,
                    GetDataConfing.Action_selectAppVersionInfo, null, false,
                    versionSelectedCallBack);
        }

    }

    /**
     * 提示用户有新版本
     */
    private void showNewVersion(final JsonMap<String, Object> info,
                                String versionName, int versionCode) {
        // 给用户提示框
        Builder builder = new Builder(SplashActivity.this);
        builder.setTitle(R.string.app_version_select);
        builder.setMessage(info.getStringNoNull("Description"));
        builder.setPositiveButton(R.string.app_version_update,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        String appName = getString(R.string.app_name);
                        util.doUpdateVersion(
                                info.getStringNoNull("VersionPath"),
                                Confing.productPath + appName + ".apk",
                                appName, R.drawable.app_icon, true);
                        jumpToNextOrSetCanJump();
                    }
                });
        builder.setNegativeButton(R.string.app_version_iknow,
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        jumpToNextOrSetCanJump();
                    }
                });
        builder.show();
    }


    IVersionSelectedCallBack versionSelectedCallBack = new IVersionSelectedCallBack() {
        @Override
        public void netError(String arg0) {
            jumpToNextOrSetCanJump();
        }

        @Override
        public boolean isUpdate(String serviceInfo, String versionName,
                                int versionCode) {
            try {
                serviceInfo = serviceInfo.substring(serviceInfo.indexOf("{"),
                        serviceInfo.lastIndexOf("}") + 1);
            } catch (Exception e) {
                e.printStackTrace();
                jumpToNextOrSetCanJump();
                return false;
            }
            if (ShowGetDataError.isCodeIsNot1(mContext, serviceInfo)) {
                List<JsonMap<String, Object>> infoData = JsonParseHelper
                        .getJsonMap_List_JsonMap(serviceInfo, JsonKeys.Key_Info);
                if (infoData.size() == 0) {
                    jumpToNextOrSetCanJump();
                } else {
                    JsonMap<String, Object> info = infoData.get(0);
                    if (info.getStringNoNull("VersionNo").equals(versionName)
                            || "".equals(info.getStringNoNull("VersionNo"))
                            || "".equals(info.getStringNoNull("VersionPath"))) {
                        jumpToNextOrSetCanJump();
                    } else {
                        showNewVersion(info, versionName, versionCode);
                    }
                }

            } else {
                jumpToNextOrSetCanJump();
            }
            return false;
        }
    };

    private void jumpToNextOrSetCanJump() {
        isCanNextActivity--;
        if (isCanNextActivity <= 0) {
            if (!Utils.isHasLogin(this)) { //是否已登录  访客登录视为不登录
                Intent intentLogin = new Intent(this, NoLoginActivity.class);
                intentLogin.putExtra(ExtraKeys.Key_Msg1, 0);
                jumpTo(intentLogin, true);

            } else {
                jumpTo(MainActivity.class, true);
                //getGoodsReturn("O73710277232805",null);
            }
        } else {
        }
    }

}